package org.glutenberg.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RandomAccessStreamReader {
	
	private StreamSource source;
	private String charset;
	private InputStream in;
	private InputStreamReader reader;
	private long position=0;
	
	public long getPosition() {
		return position;
	}

	public RandomAccessStreamReader(StreamSource source, String charset) throws IOException{
		this.source = source;
		this.charset = charset;
		this.reset();
	}
	
	public int read() throws IOException{
		int ret = this.reader.read();
		if(ret>=0) position++;
		return ret;
	}
	
	public void close() throws IOException{
		this.reader.close();
	}
	
	public void reset() throws IOException{
		if(this.reader!=null) this.reader.close();
		this.position = 0;
		this.in = source.openInputStream();
		this.reader = new InputStreamReader(in, this.charset);
	}
	
	public void seek(long position) throws IOException{
		if(this.position<position){
			this.in.skip(position-this.position);
			this.position = position;
		}
		else if(position<this.position) {
			this.reset();
			this.in.skip(position);
			this.position = position;
		}
	}
	
}
